package com.lottery.im.module.result.ui.game;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.R;
import com.lottery.im.api.result.entity.GameHistoryInfo;
import com.lottery.im.api.result.entity.ResultInfo;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.common.WeakReferenceHandler;
import com.lottery.im.constant.Constants;
import com.lottery.im.module.result.adapter.result.statistics.History28Adapter;
import com.lottery.im.module.result.presenter.GameDetailPresenter;
import com.lottery.im.module.result.view.GameDetailView;
import com.lottery.im.util.TimerUtils;
import com.lottery.im.util.rxbus.RxBus;
import com.lottery.im.view.G28VideoView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class Game28Fragment extends BaseSwipeFragment<GameDetailPresenter>
    implements GameDetailView {
  private final static String GAME_TYPE_KEY = "GAME_TYPE_KEY";
  private final static String GAME_TYPE_NAME_KEY = "GAME_TYPE_NAME_KEY";

  public static Game28Fragment create(String gameType, String gameTypeName) {
    Game28Fragment fragment = new Game28Fragment();
    Bundle b = new Bundle();
    b.putString(GAME_TYPE_KEY, gameType);
    b.putString(GAME_TYPE_NAME_KEY, gameTypeName);
    fragment.setArguments(b);
    return fragment;
  }

  @SuppressLint("HandlerLeak")
  private class MyHandler extends WeakReferenceHandler<BaseSwipeFragment> {
    public MyHandler(BaseSwipeFragment reference) {
      super(reference);
    }

    protected void handleMessage(BaseSwipeFragment reference, Message msg) {
      switch (msg.what) {
        case 0:
          if (null == mActivity || mActivity.isFinishing()) {
            return;
          }
          if (!"1".equals(isResult)) {
            presenter.queryAllGameTypeResult();
            presenter.queryGameTypeResult(mGameType, startRow, pageSize);
          }
          break;
      }
    }
  }

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.tv_game_sueId) TextView mTvSueId;
  @BindView(R.id.tv_result1) TextView mTvResult1;
  @BindView(R.id.tv_result2) TextView mTvResult2;
  @BindView(R.id.tv_result3) TextView mTvResult3;
  @BindView(R.id.tv_sum) TextView mTvSum;
  @BindView(R.id.tv_he_zhi) TextView mTvHeZhi;
  @BindView(R.id.tv_game_time) TextView mTvTime;
  @BindView(R.id.progressBar) ProgressBar mProgressBar;
  @BindView(R.id.refreshLayout) RefreshLayout mRefreshLayout;
  @BindView(R.id.history_list) RecyclerView mRecyclerView;
  @BindView(R.id.g28_video_view) G28VideoView mG28VideoView;
  private List<GameHistoryInfo> mHistoryList = new ArrayList<>();
  private History28Adapter mAdapter;
  private MyCountDownTimer mCountDownTimer;
  private String mGameType;
  private String mGameTypeName;
  private int startRow = 0;
  private int pageSize = 30;
  private MyHandler mHandler;
  private Timer timer;
  private String isResult;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_game_28;
  }

  @Override protected void initPresenter() {
    presenter = new GameDetailPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {
    if (getArguments() == null) {
      popBackStack();
      return;
    } else {
      RxBus.get().register(this);
      mGameType = getArguments().getString(GAME_TYPE_KEY);
      mGameTypeName = getArguments().getString(GAME_TYPE_NAME_KEY);
      mTvTitle.setText(mGameTypeName);
      mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
      mAdapter = new History28Adapter(mHistoryList);
      mRecyclerView.setAdapter(mAdapter);
      RecyclerViewDivider.with(mActivity)
          .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
          .size((int) mActivity.getResources().getDimension(R.dimen.line_size_dp1))
          .hideLastDivider()
          .build()
          .addTo(mRecyclerView);
      mRefreshLayout.setOnRefreshListener(refreshLayout -> {
        refreshLayout.finishRefresh(1000);
        startRow = 0;
        presenter.queryGameTypeResult(mGameType, startRow, pageSize);
      });
      mRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
        refreshLayout.finishLoadMore(0);
        startRow += pageSize;
        presenter.queryGameTypeResult(mGameType, startRow, pageSize);
      });
      presenter.queryAllGameTypeResult();
      presenter.queryGameTypeResult(mGameType, startRow, pageSize);
      mHandler = new MyHandler(this);
      timer = new Timer();
      timer.schedule(new TimerTask() {
        @Override
        public void run() {
          if (mHandler != null) {
            Message message = mHandler.obtainMessage(0);
            mHandler.handleMessage(message);
          }
        }
      }, 0, 5000);
    }
  }

  @OnClick({ R.id.iv_back, R.id.btn_anim })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.btn_anim:
        mG28VideoView.changeVisible();
        break;
    }
  }

  @Override public void queryHistorySuccess(List<GameHistoryInfo> list) {
    if (startRow == 0) {
      mHistoryList.clear();
    }
    for (int i = 0; i < list.size(); i++) {
      GameHistoryInfo info = list.get(i);
      String issueId = info.getIssueId();
      String resultDate = info.getResultDate();
      String resultStr = info.getResultStr();
      if (resultDate.length() >= 12) {
        info.setDate(resultDate.substring(8, 10) + ":" + resultDate.substring(10, 12));
      }
      info.setIsSueId(
          issueId.length() >= 3 ? issueId.substring(issueId.length() - 3, issueId.length()) + "期"
              : issueId + "期");
      if (resultStr.length() > 0) {
        String[] str = resultStr.split(",");
        if (str.length >= 3) {
          info.setStringStr(Arrays.asList(str));
          int w = Integer.parseInt(str[0]);
          int q = Integer.parseInt(str[1]);
          int b = Integer.parseInt(str[2]);
          int sum = w + q + b;
          String dx;
          String ds;
          if (sum >= 14) {
            dx = "大";
          } else {
            dx = "小";
          }
          if (sum % 2 == 0) {
            ds = "双";
          } else {
            ds = "单";
          }
          info.setHeZhi(sum + "");
          info.setDaXiao(sum + "  " + dx + "  " + ds);
        }
      }
    }
    mHistoryList.addAll(list);
    mAdapter.notifyDataSetChanged();
  }

  @SuppressLint("SetTextI18n") @Override public void querySuccess(List<ResultInfo> list) {
    for (ResultInfo resultInfo : list) {
      if (mGameType.equals(resultInfo.getGameType())) {
        mTvSueId.setText(resultInfo.getIssueId());
        String resultStr = resultInfo.getResultStr();
        if (resultStr.length() > 0) {
          String[] str = resultStr.split(",");
          if (str.length >= 3) {
            int w = Integer.parseInt(str[0]);
            int q = Integer.parseInt(str[1]);
            int b = Integer.parseInt(str[2]);
            int sum = w + q + b;
            String dx;
            String ds;
            if (sum >= 14) {
              dx = "大";
            } else {
              dx = "小";
            }
            if (sum % 2 == 0) {
              ds = "双";
            } else {
              ds = "单";
            }
            mTvResult1.setText(str[0]);
            mTvResult2.setText(str[1]);
            mTvResult3.setText(str[2]);
            mTvSum.setText(sum + "");
            mTvHeZhi.setText(sum + "    " + dx + "    " + ds);
            mG28VideoView.setTermAndResult(resultInfo.getIssueId(), str, sum + "", dx, ds);
          }
        }
        long closeTime = resultInfo.getGMTcloseTime();
        long openTime = resultInfo.getGMTopenTime();
        long curTime = resultInfo.getGMTcurTime();
        isResult = resultInfo.getIsResult();
        mProgressBar.setMax((int) (closeTime - openTime) / 1000);
        if (closeTime - curTime > 0 && "1".equals(isResult)) {
          if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
          }
          mCountDownTimer =
              new MyCountDownTimer(closeTime - openTime, closeTime - curTime,
                  Constants.COUNT_DOWN_INTERVAL);
          mCountDownTimer.start();
        } else {
          mProgressBar.setProgress((int) (closeTime - openTime) / 1000);
          mTvTime.setText(R.string.opening);
          mG28VideoView.setOpening();
          if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
          }
        }
      }
    }
  }

  class MyCountDownTimer extends CountDownTimer {
    private long max;

    public MyCountDownTimer(long max, long millisInFuture, long countDownInterval) {
      //微调防止跳过
      super(millisInFuture + millisInFuture * 2 / countDownInterval, countDownInterval);
      this.max = max;
    }

    @Override
    public void onTick(long millisUntilFinished) {
      if (mTvTime == null) return;
      mTvTime.setText(TimerUtils.formatDuring2(millisUntilFinished));

      if (mHistoryList.size() > 0) {
        mG28VideoView.setTime(TimerUtils.formatDuring2(millisUntilFinished),
            mHistoryList.get(0).getResultStr().split(","));
      } else {
        mG28VideoView.setTime(TimerUtils.formatDuring2(millisUntilFinished), null);
      }

      mProgressBar.setProgress((int) max / 1000 - (int) millisUntilFinished / 1000);
    }

    @Override
    public void onFinish() {
      cancel();
      mTvTime.setText(R.string.opening);
      mG28VideoView.setOpening();
      isResult = "0";
    }
  }

  @Override public void onDestroy() {
    super.onDestroy();
    RxBus.get().unRegister(this);
    if (mCountDownTimer != null) {
      mCountDownTimer.cancel();
    }
    mCountDownTimer = null;
    mHandler.removeCallbacksAndMessages(null);
    mHandler = null;
    mG28VideoView.cancel();
  }
}
